# -*- coding:utf-8 -*-

from sys import platform
from os import stat, chmod, makedirs
from os.path import join, expanduser, exists
from shutil import copy2
from setuptools.command.install import install
from kdui2py.fileutil import get_file_realpath

# 修改project_name即可打包，其他地方不用修改
project_name = "kdui2py"


class install_cmd(install):
    def run(self):
        install.run(self)
        try:
            if platform == "win32":
                script_file = join(
                    self._get_desktop_folder(), project_name + '.bat')
                with open(script_file, "w") as f:
                    f.write("@echo off\r\nstart " +
                            project_name + ".exe")
            elif platform == "linux":
                script_file = join(
                    self._get_desktop_folder(), project_name + '.sh')
                with open(script_file, "w") as f:
                    f.write("#!/bin/sh\n" + project_name)
                    st = stat(script_file)
                    chmod(script_file, st.st_mode)

                # 复制图标
                user_icon_dir = join(
                    expanduser('~'), '.local/share/icons/hicolor/apps/')
                if not exists(user_icon_dir):
                    makedirs(user_icon_dir)
                copy2(get_file_realpath(
                    "kdui2py.jpg"), user_icon_dir)

                # 复制桌面快捷方式
                user_applicaption_dir = join(
                    expanduser('~'), '.local/share/applications')
                if not exists(user_applicaption_dir):
                    makedirs(user_applicaption_dir)

                desktop_content = """[Desktop Entry]
Exec=kdui2py
Icon={}
Terminal=false
Type=Application
StartupNotify=true
Categories=GTK;Development
Name=kdui2py
Comment=Qt UI文件转换器
Name[zh_CN]=Qt UI文件转换器

""".format(join(user_icon_dir, "kdui2py.jpg"))
                desktop_path = join(user_applicaption_dir, "kdui2py.desktop")

                with open(desktop_path, "w+") as f:
                    f.write(desktop_content)
                copy2(desktop_path, self._get_desktop_folder())
        except Exception as e:
            print("can not create start script." + str(e))

    def _get_desktop_folder(self):
        import subprocess
        try:
            return subprocess.check_output(['xdg-user-dir',
                                            'DESKTOP']).decode('utf-8').strip()
        except Exception:
            return join(expanduser('~'), 'Desktop')
